package com.example.wei.mvp.api;


import com.example.wei.mvp.ui.bean.PersonResult;
import com.example.wei.mvp.ui.bean.TestBean;
import com.sina.common.okhttp.Constant;
import com.sina.common.okhttp.bean.HttpResult;

import java.io.File;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Part;


/**
 * Created by Administrator on 2017/1/16.
 */

public class Api {

    public static Api instance;
    private ApiService service;

    public Api(OkHttpClient okHttpClient) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.HOSTURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        service = retrofit.create(ApiService.class);
    }


    public static Api getInstance(OkHttpClient okHttpClient) {

        if (instance == null)
            instance = new Api(okHttpClient);
        return instance;
    }


    /**
     * 获取登录验证码
     * @param mobile
     * @return
     */
    public Observable<HttpResult> sendVerifyCode(String mobile) {
        return service.sendVerifyCode(mobile);
    }

    public Observable<TestBean> getUser() {
        return service.getUser();
    }

    public Observable<PersonResult> getUserInfo(String name, int age, String gender) {
        return service.getUserInfo(name,age,gender);
    }

    public Observable<PersonResult> getUserPost(String name, int age, String gender) {
        return service.getUserPost(name,age,gender);
    }


    public Observable<HttpResult> psotImage(String type, File file) {
//        RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
        // 创建 RequestBody，用于封装 请求RequestBody
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
        return service.psotImage(type,body);
    }

}
